package snsdbook.engine;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import snsdbook.beans.ContentBean;
import util.SQLUtil;

public abstract class PaginatedContentList {
  
  public static final int kPaginationSize = 6;
  
  public static void Display(int ids[],
                             boolean show_searchbar,
                             boolean show_comments,
                             boolean show_pagination,
                             boolean is_short,
                             int page,
                             HttpServletRequest request,
                             HttpServletResponse response)
                             throws IOException, ServletException {
    
    ArrayList<ContentBean> beans = new ArrayList<ContentBean>();
    for (int i = kPaginationSize * page; i < kPaginationSize * (page+1); ++i) {
      if (i >= 0 && i < ids.length) {
        beans.add(new ContentBean(ids[i], i - kPaginationSize * page, is_short));
      }
    }
    
    request.setAttribute("contents", beans);
    
    if (show_comments) {
      request.setAttribute("show_comments", "true");
    }
    if (show_searchbar) {
      request.setAttribute("show_searchbar", "true");
    }
    if (show_pagination) {
      request.setAttribute("show_pagination", "true");
    }
    
    request.setAttribute("page", String.valueOf(page));
    
    // Create all except pages link
    String current_link = request.getRequestURL().toString();
    boolean init = true;
    for (Object param : request.getParameterMap().keySet()) {
      String key = (String)param;
      if (key.equals("page")) continue;
      if (init) {
        current_link += "?";
        init = false;
      } else {
        current_link += "&";
      }
      String[] params = request.getParameterValues(key);
      for (int i = 0; i < params.length; ++i) {
        if (i > 0) current_link += "&";
        current_link += key + "=" + params[i];
      }
    }
    
    String prev_page = null;
    String next_page = null;
    if (init) {
      next_page = current_link + "?page=" + String.valueOf(page + 1);
      prev_page = current_link + "?page=" + String.valueOf(page - 1);
    } else {
      next_page = current_link + "&page=" + String.valueOf(page + 1);
      prev_page = current_link + "&page=" + String.valueOf(page - 1);
    }
    request.setAttribute("prev_page", prev_page);
    request.setAttribute("next_page", next_page);
    
    // Setting list of tags
    ArrayList<String> tags = new ArrayList<String>();
    String[] all_tags = SQLUtil.Query("SELECT nama_tag FROM tag");
    for (String tag : all_tags) {
      tags.add(tag);
    }
    request.setAttribute("all_tags", tags);
    
    RequestDispatcher view = request.getRequestDispatcher("/ContentList.jsp");
    view.forward(request, response);
  }
}
